<?php
error_reporting(E_ERROR | E_WARNING );
function to_camel_case($str, $capitalise_first_char = false) {
    if($capitalise_first_char) {
      $str[0] = strtoupper($str[0]);
    }
    $func = create_function('$c', 'return strtoupper($c[1]);');
    return preg_replace_callback('/_([a-z])/', $func, $str);
  }


$handle = fopen ("php://stdin","r");
/*echo "
.-. .-. .-. . . . . 
`-. |-   |  |-| | | 
`-' `-'  '  ' ` `-' 
";*/
$settings = parse_ini_file('settings.ini');


echo "host [{$settings['host']}] :";
$host = fgets($handle);
$host = trim($host) ? trim($host) : $settings['host'];
echo "username [{$settings['username']}] :";
$username = fgets($handle);
$username = trim($username) ? trim($username) : $settings['username'];
echo "password [{$settings['password']}] :";
$password = fgets($handle);
$password = trim($password) ? trim($password) : $settings['password'];
echo "database [{$settings['database']}] :";
$database =  fgets($handle);
$database = trim($database) ? trim($database) : $settings['database'];
echo "table:";
$table =  fgets($handle);
$table = trim($table);
echo "Connecting : $username:$password@$host ";

$con = mysql_connect($host,$username,$password);

mysql_select_db($database,$con);

$rs = mysql_query("describe `$table` ",$con);

$fields = array();
$class_name = to_camel_case($table,true);
$output = "
<?php
/**
 * {$settings['bundlePath']}\\$class_name
 *
 * @ORM\Table(name=\"$table\")
 * @ORM\Entity
 */
class ".$class_name." { ";

while($row = mysql_fetch_assoc($rs)){
	
	$columnName =  $row['Field'];
	$propertyName = $row['Key']=='PRI'? 'id' : to_camel_case($columnName);
	$length=', length=145';
	if($row['Type']){
		if(strpos(strtolower($row['Type']),'int')!== FALSE){
			$type = "integer";
			$length='';
		}
		if(strpos($row['Type'],'varchar')!== FALSE){
			$type = "string";
		}
		if(strpos(strtolower($row['Type']),'date')!== FALSE || strpos(strtolower($row['Type']),'timestamp')!== FALSE){
			$type = "datetime";
			$length='';
		}
	}
	
	$primaryKeyStuff = $row['Key']=='PRI'? "* @ORM\Id \n     * @ORM\GeneratedValue(strategy=\"AUTO\")" : '';
	$output.= "
	/**
     * @var $type $propertyName
	 * $primaryKeyStuff
     *
     * @ORM\Column(name=\"$columnName\", type=\"$type\" $length )
     */
    private \$$columnName;
	";
}
$output.= "}
?>";
$folder_name  =  $settings['folder'] ? $settings['folder'] : 'entities' ;

if(!file_exists($folder_name)){
	mkdir($folder_name);
}
$file = fopen($folder_name.'/'.to_camel_case($table,true).'.php',"w");
fputs($file,$output);
fclose($file);
echo "\n Generated ".to_camel_case($table,true).'.php';
?>